package com.woniuxy.house.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.woniuxy.house.peopertiesentity.JwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: 老谭（<a href="http://www.woniuxy.com">蜗牛学苑</a>）
 */
@Component
public class JwtUtil {
    @Autowired
    private JwtProperties jwtProperties;

    //创建
    public  String createJWT(int id, String account) {
        DateTime now = DateTime.now();
        DateTime newTime = now.offsetNew(DateField.SECOND, jwtProperties.getExpireSeconds());
        Map<String, Object> payload = new HashMap<String, Object>();
        //签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        //过期时间
        payload.put(JWTPayload.EXPIRES_AT, newTime);
        //生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);
        //载荷
        payload.put("id", id);
        payload.put("account", account);
        String token = JWTUtil.createToken(payload, jwtProperties.getSecret().getBytes());
        return token;
    }

    //解析
    public boolean verifyJWT(String token) {
        //解析出jwt对象
        JWT jwt = JWTUtil.parseToken(token);
        //密钥是否正确
        boolean verifyKey = jwt.setKey(jwtProperties.getSecret().getBytes()).verify();
        //验证是否过期
        boolean verifyTime = jwt.validate(0);
        return verifyKey&&verifyTime;
    }

    //解析出用户的id和账号
    public Object verifyJWTGetUserId(String token,String o) {
        //解析出jwt对象
        JWT jwt = JWTUtil.parseToken(token);
        return jwt.getPayload(o);
    }
}
